import Vue from 'vue'
import VueRouter from 'vue-router'
import { Toast } from 'vant'
import routers from './routers'
import { getToken } from '@/utils/Token.js'
import Tool from '@/utils/tool'

Vue.use(VueRouter)

const LOGIN_PAGE_NAME = 'login'

const router = new VueRouter({
  routes: routers,
  mode: 'history',
  base: process.env.NODE_ENV === 'production' ? '/h5' : '/'
})

const setTitle = (routeItem, vm) => {
  // const pageTitle = vm.$_showRoutesI18n(routeItem, vm)
  const pageTitle = routeItem.name
  // const resTitle = pageTitle ? `${vm.$Config.title} - ${pageTitle}` : vm.$Config.title
  let resTitle = ''
  pageTitle ? resTitle = pageTitle : resTitle = vm.$Config.title
  window.document.title = resTitle
  let isClient = Tool.isClient()
  if (isClient) {
    window.location.href = 'yggtitle://' + encodeURIComponent(resTitle)
  }
}

const appLocation = (to, next) => {
  let baseURL = process.env.NODE_ENV === 'production' ? '/h5' : ''
  if (Tool.isClient()) {
    if (to.query.isclient) {
      next()
    } else {
      let params = to.query
      params.isclient = 1
      let urlParams = Tool.urlencode(params)
      window.location.href = baseURL + to.path + '?' + urlParams
      // window.location.replace =
    }
  } else {
    next() // 跳转
  }
}

let loadingInstance = null
// 路由-全局前置守卫: 页面加载开始、登录与否判断
router.beforeEach((to, from, next) => {
  // console.log('beforeEach:', to, from)
  // loadingInstance = Toast.loading({
  //   mask: true,
  //   duration: 0, // 持续展示 toast
  //   forbidClick: true, // 禁用背景点击
  //   loadingType: 'spinner',
  //   message: '加载中...'
  // })

  const token = getToken()
  // console.log(token)
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    // next({ name: LOGIN_PAGE_NAME }) // 跳转到登录页
    appLocation(to, next)
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    appLocation(to, next)
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({ name: 'home' }) // 跳转到homeName页
  } else {
    appLocation(to, next)
  }
})

// 路由-全局后置钩子: 设置title、页面加载结束、滚动到顶部、
router.afterEach((to, from) => {
  // console.log('afterEach', loadingInstance)
  setTitle(to, router.app)
  // console.log(loadingInstance)
  if (loadingInstance) {
    Toast.clear()
    // window.setTimeout(function () {
    //   Toast.clear()
    // }, 300)
  }
  Toast.clear()
  if (to.path !== '/active/become_vip' && to.path !== '/merber/index' && to.path !== '/active/national_day') {
    window.setTimeout(function () {
      window.scrollTo(0, 0)
    }, 100)
  }
})

export default router

// 全局前置守卫
// router.beforeEach((to, from, next) => {
//   /* must call `next` */
// })

// 全局解析守卫
// router.beforeResolve((to, from, next) => {
//   /* must call `next` */
// })

// 全局后置钩子
// router.afterEach((to, from) => {})
